package com.stylefeng.guns.core.filter;


import com.stylefeng.guns.core.util.SpringContextHolder;
import com.stylefeng.guns.modular.shop.service.ITGoodsClassService;
import com.stylefeng.guns.modular.shop.service.ITMemberService;
import com.stylefeng.guns.modular.shop.service.ITOrderService;
import com.stylefeng.guns.modular.shop.service.impl.TMemberServiceImpl;
import com.stylefeng.guns.persistence.shop.model.TMember;
import com.stylefeng.web.utils.SessionUtil;
import com.stylefeng.web.wx.Constant;
import com.stylefeng.web.wx.WxConfigProperties;
import com.stylefeng.web.wx.service.impl.WeixinService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : Hui.Wang [huzi.wh@gmail.com]
 * @version : 1.0
 * @created on  : 2017/6/28  下午4:18
 */

public class WxAuthFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(WxAuthFilter.class);



    ITMemberService itMemberService =new TMemberServiceImpl();

    SessionUtil sessionUtil = new SessionUtil();



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
        configStorage.setAppId(WxConfigProperties.appid);
        configStorage.setSecret(WxConfigProperties.appsecret);
        configStorage.setToken(WxConfigProperties.token);
        configStorage.setAesKey(WxConfigProperties.aeskey);
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(configStorage);
        MDC.put("logId", RandomStringUtils.randomNumeric(8));

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String uri = httpServletRequest.getRequestURI();
        logger.info("request url={}?{}", uri, httpServletRequest.getQueryString());
        logger.info("doFilter getHeadersInfo:{}", getHeadersInfo(httpServletRequest));

        String wxOauth2Code = request.getParameter("code");
        String state = request.getParameter("state");
        TMember user = sessionUtil.getCurrentUser();
        logger.info("currentUser:{}", user);

        if (uri.startsWith(Constant.WX_H5_URI) && null == user
                && (StringUtils.isEmpty(state) || !sessionUtil.isExistState(state))) {
            logger.info("current user is null");

            String param = httpServletRequest.getQueryString();
            String redirectUrl = WxConfigProperties.pageDomain + uri;
            if (StringUtils.isNotBlank(param)) {
                redirectUrl += "?" + param;
            }
            String scope = "snsapi_userinfo";
            String wxOauth2Url = wxMpService.oauth2buildAuthorizationUrl(redirectUrl, scope, sessionUtil.getNewWxState());

            logger.info("wxOauth2Url={} scope={} state={} redirectUrl={}", wxOauth2Url, scope, state, redirectUrl);
            httpServletResponse.sendRedirect(wxOauth2Url);
            //跳转到 微信登录页面
            return;
        }

        if (uri.startsWith(Constant.WX_H5_URI) && null == user
                && (StringUtils.isNotEmpty(wxOauth2Code) && StringUtils.isNotEmpty(state))
                && sessionUtil.isExistState(state)) {

            //处理用户
            try {
                user = itMemberService.getByWxOauthCode(wxOauth2Code);
                user.setToken(sessionUtil.generateToken());
                sessionUtil.setCurrentUser(httpServletResponse, user);
                Long uid = user.getId();
                if (null == uid) {
                    logger.info("----go to signup page------");
                    String toUrl = WxConfigProperties.pageDomain + Constant.VIEW_SIGNUP + "?token=" + user.getToken();
                    httpServletResponse.sendRedirect(toUrl);
                    return;
                }else {
                    itMemberService.insert(user);
                    String toUrl = WxConfigProperties.pageDomain + "/wap";
                    httpServletResponse.sendRedirect(toUrl);
                    return;
                }
            } catch (WxErrorException e) {
                logger.error("doFilter error.", e);
            }
        }
        chain.doFilter(httpServletRequest, response);
    }

    @Override
    public void destroy() {
    }

}
